package com.drinks.yiniang.ui.fragment.community;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.community.CommunityActAdapter;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.comment.CommentSubmitJson;
import com.drinks.yiniang.entity.common.AdBannerEntity;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.community.CommunityActJson;
import com.drinks.yiniang.entity.community.CommunityNewsJson;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.ui.activity.community.CommunityActCommentsActivity;
import com.drinks.yiniang.ui.widget.dialog.CommentBoxDialog;
import com.drinks.yiniang.ui.widget.dialog.ShareDialog;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.ActivityUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseLazyFragment;
import com.hansen.library.ui.widget.image.RatioRoundImageView;
import com.hansen.library.utils.ArithmeticUtil;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;

/**
 * 社区活动页面
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class CommunityActFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.OnItemChildClickListener, CommentBoxDialog.OnSendCommentListener, BaseQuickAdapter.RequestLoadMoreListener {

    private final String TYPE_API_DO_COLLECT = "1";
    private final String TYPE_API_DO_LIKE = "0";

    private MSwipeRefreshLayout refresh_community_act;
    private BaseRecyclerView rcv_community_act;
    //header view
    //banner
    private RatioRoundImageView iv_community_act_banner;

    private CommentBoxDialog mCommentBoxDialog;

    private CommunityActAdapter mAdapter;

    private AdBannerEntity mBanner;

    private int mPages;

    public CommunityActFragment() {
        // Required empty public constructor
    }

    public static CommunityActFragment newInstance() {
        return new CommunityActFragment();
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_community_act;
    }

    @Override
    protected void initView(View mView) {
        refresh_community_act = mView.findViewById(R.id.refresh_community_act);

        rcv_community_act = mView.findViewById(R.id.rcv_community_act);
    }

    @Override
    protected void initData() {
        mContext = getContext();

        initAdapter();
    }

    private void initAdapter() {
        rcv_community_act.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_community_act.addItemDecoration(ItemSpacesDecoration.getItemDPDecoration(10));

        mAdapter = new CommunityActAdapter(mContext, new ArrayList<CommunityActJson.CommunityActList>());
        mAdapter.addHeaderView(getHeaderView());
        mAdapter.setHeaderAndEmpty(true);
        mAdapter.setCenterEmpty(getLayoutInflater(), rcv_community_act);
        mAdapter.bindToRecyclerView(rcv_community_act);
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_community_act, (ViewGroup) rcv_community_act.getParent(), false);

        iv_community_act_banner = mHeaderView.findViewById(R.id.iv_community_act_banner);

        iv_community_act_banner.setOnClickListener(this);

        return mHeaderView;
    }

    @Override
    protected void listener() {
        refresh_community_act.setOnRefreshListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnLoadMoreListener(this, rcv_community_act);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_community_act_banner:
                if (mBanner == null) {
                    return;
                }

                ActivityUtils.startActivityByAdType(mContext, mBanner.getType(), mBanner.getValue());
                break;
            default:
                break;
        }
    }

    @Override
    protected void lazyLoadData() {
        getActivityNews();
    }

    @Override
    public void onRefresh() {
        getActivityNews();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        CommunityActJson.CommunityActList data = mAdapter.getItem(position);

        if (data == null) {
            return;
        }

        Intent mIntent;

        switch (view.getId()) {
            case R.id.iv_community_act_three_dot://分享
                ShareDialog dialog = ShareDialog.newInstance("", data.getId(), true, true);

                dialog.show(getChildFragmentManager(), Constants.TAG_SHARE_DIALOG);
                break;
            case R.id.tv_community_act_collect://收藏
                doCollectOrLike(TYPE_API_DO_COLLECT, data, position);
                break;
            case R.id.tv_community_act_like://点赞
                doCollectOrLike(TYPE_API_DO_LIKE, data, position);
                break;
            case R.id.tv_community_act_total_comments:
                mIntent = new Intent(mContext, CommunityActCommentsActivity.class);
                mIntent.putExtra(Constants.KeyCommunityId, data.getId());
                startActivity(mIntent);
                break;
            case R.id.tv_community_act_comments_add://活动评论
                mCommentBoxDialog = CommentBoxDialog.newInstance(position);
                mCommentBoxDialog.show(getChildFragmentManager(), Constants.TAG_COMMENTS_DIALOG);
                break;
            default:
                break;
        }
    }

    @Override
    public void sendComment(String comment, final int position) {
        CommunityActJson.CommunityActList data = mAdapter.getItem(position);

        if (data == null || StringUtils.isEmpty(data.getId())) {
            return;
        }

        if (StringUtils.isEmpty(comment)) {
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityActComments(data.getId(), comment, null,
                new APIRequestCallback<CommentSubmitJson, Tuple2<Integer, String>>() {
                    @Override
                    public void onSuccess(CommentSubmitJson res) {
                        if(mCommentBoxDialog != null) {
                            mCommentBoxDialog.dismiss();
                        }

                        CommunityActJson.CommunityActList data = mAdapter.getItem(position);

                        if(data == null) {
                            return;
                        }

                        if(data.getComment() == null) data.setComment(new ArrayList<CommunityActJson.CommunityActComments>());

                        if(data.getComment().size() >= 2) {
                            for(int i = data.getComment().size() - 1; i >= 0; i--) {
                                if(i >= 1) {
                                    data.getComment().remove(i);
                                }
                            }
                        }

                        CommunityActJson.CommunityActComments commentData = new CommunityActJson.CommunityActComments();
                        commentData.setContent(res.getData().getContent());
                        commentData.setId(res.getData().getId());
                        commentData.setNickname(res.getData().getNickname());

                        data.setComment_count(ArithmeticUtil.add(data.getComment_count(), 1));
                        data.getComment().add(0, commentData);

                        mAdapter.setData(position, data);
                    }

                    @Override
                    public void onError(Tuple2<Integer, String> error) {
                        ToastUtils.showShort(error._2);
                    }

                    @Override
                    public void onComplete() {
                        dismissDialog();
                    }
                });
    }

    @Override
    public void onLoadMoreRequested() {
        CommunityApiIO.getInstance().getCommunityActivityNew(mPages, new APIRequestCallback<CommunityActJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityActJson res) {
                if (mAdapter == null) {
                    return;
                }

                mPages++;
                mAdapter.addData(res.getData().getData());
                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mAdapter.loadMoreComplete();
                } else {
                    mAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取活动列表
    private void getActivityNews() {
        if (!refresh_community_act.isRefreshing()) {
            showLoadingDialog();
        }

        mPages = 1;

        CommunityApiIO.getInstance().getCommunityActivityNew(mPages, new APIRequestCallback<CommunityActJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(CommunityActJson res) {
                if (mAdapter == null) {
                    return;
                }

                mPages++;

                setBannerData(res.getData().getBanner());

                mAdapter.getData().clear();
                mAdapter.addData(res.getData().getData());
                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mAdapter.loadMoreComplete();
                } else {
                    mAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                refresh_community_act.setRefreshing(false);
                dismissDialog();
            }
        });
    }

    private void setBannerData(AdBannerEntity data) {
        if (data == null) {
            iv_community_act_banner.setVisibility(View.GONE);
            return;
        }

        mBanner = data;

        iv_community_act_banner.setVisibility(View.VISIBLE);
        GlideUtils.loadExchangeAdList(mContext, iv_community_act_banner, data.getCover_url());
    }

    private void doCollectOrLike(final String type, final CommunityActJson.CommunityActList data, final int pos) {
        if(!ActivityUtils.isLogined(this, mContext, true)) {
            return;
        }

        if (StringUtils.isEmpty(data.getId())) {
            ToastUtils.showShort(R.string.text_community_not_exist);
            return;
        }

        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityActCollectOrLike(type, data.getId(), new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if(CommonUtils.isArrayIndexOutOfBounds(mAdapter.getData(), pos)) {
                    return;
                }

                if(TYPE_API_DO_COLLECT.equals(type)) {
                    data.setCollect_count(res.getData());
                    data.setIs_collect(Constants.STATUS_GLOBAL_YES.equals(data.getIs_collect()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);
                } else {
                    data.setLike_count(res.getData());
                    data.setIs_like(Constants.STATUS_GLOBAL_YES.equals(data.getIs_like()) ? Constants.STATUS_GLOBAL_NO : Constants.STATUS_GLOBAL_YES);
                }

                mAdapter.setData(pos, data);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }
}
